package org.linlinjava.litemall.admin.controller;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_CATEGORY_HAS_GOODS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.linlinjava.litemall.admin.beans.annotation.LogAnno;
import org.linlinjava.litemall.admin.beans.vo.CategoryVo;
import org.linlinjava.litemall.admin.service.CategoryService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCategory;
import org.linlinjava.litemall.db.service.LitemallCategoryService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;

/**
 * 管理类别控制器
 *
 * @author yliyun
 * @date 2022/09/14
 */
@RestController
@RequestMapping("/admin/category")
@Validated
public class AdminCategoryController {

    /**
     * litemall类别服务
     */
    @Autowired
    private LitemallCategoryService litemallCategoryService;
    /**
     * 目录服务
     */
    @Autowired
    private CategoryService categoryService;
    /**
     * litemall商品服务
     */
    @Autowired
    private LitemallGoodsService litemallGoodsService;

    /**
     * 列表
     *
     * @return {@link Object}
     */
    @GetMapping("/list")
    @LogAnno
    @ApiOperation("获取分类列表（含三级）")
    public Object list() {
        List<CategoryVo> categoryVoList = new ArrayList<>();

        List<LitemallCategory> categoryList = litemallCategoryService.queryByPid(0);
        for (LitemallCategory category : categoryList) {
            CategoryVo categoryVO = getCategoryVo(category);

            List<CategoryVo> children = new ArrayList<>();
            List<LitemallCategory> subCategoryList = litemallCategoryService.queryByPid(category.getId());
            for (LitemallCategory subCategory : subCategoryList) {
                CategoryVo subCategoryVo = getCategoryVo(subCategory);

                List<CategoryVo> childrenLThree = new ArrayList<>();
                List<LitemallCategory> litemallCategories = litemallCategoryService.queryByPid(subCategory.getId());
                if(!CollectionUtils.isEmpty(litemallCategories)){
                    for(LitemallCategory litemallCategory : litemallCategories){
                        CategoryVo categoryVoThree = getCategoryVo(litemallCategory);
                        childrenLThree.add(categoryVoThree);
                    }
                }

                subCategoryVo.setChildren(childrenLThree);
                children.add(subCategoryVo);
            }

            categoryVO.setChildren(children);
            categoryVoList.add(categoryVO);
        }

        return ResponseUtil.okList(categoryVoList);
    }

    /**
     * 得到类别签证官
     *
     * @param litemallCategory litemall类别
     * @return {@link CategoryVo}
     */
    private CategoryVo getCategoryVo(LitemallCategory litemallCategory) {
        CategoryVo categoryVoThree = new CategoryVo();
        categoryVoThree.setId(litemallCategory.getId());
        categoryVoThree.setDesc(litemallCategory.getDesc());
        categoryVoThree.setIconUrl(litemallCategory.getIconUrl());
        categoryVoThree.setPicUrl(litemallCategory.getPicUrl());
        categoryVoThree.setKeywords(litemallCategory.getKeywords());
        categoryVoThree.setName(litemallCategory.getName());
        categoryVoThree.setNameEn(litemallCategory.getNameEn());
        categoryVoThree.setLevel(litemallCategory.getLevel());
        categoryVoThree.setPid(litemallCategory.getPid());
        categoryVoThree.setSortOrder(litemallCategory.getSortOrder());
        return categoryVoThree;
    }

    /**
     * 验证
     *
     * @param category 类别
     * @return {@link Object}
     */
    private Object validate(LitemallCategory category) {
        String name = category.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        String level = category.getLevel();
        if (StringUtils.isEmpty(level)) {
            return ResponseUtil.badArgument();
        }
        if (!level.equals("L1") && !level.equals("L2") && !level.equals("L3")) {
            return ResponseUtil.badArgumentValue();
        }

        Integer pid = category.getPid();
        if ((level.equals("L2")||level.equals("L3")) && (pid == null)) {
            return ResponseUtil.badArgument();
        }

        return null;
    }

    /**
     * 创建
     *
     * @param category 类别
     * @return {@link Object}
     */
    @PostMapping("/create")
    @LogAnno
    @ApiOperation("创建分类")
    public Object create(@RequestBody LitemallCategory category) {
        Object error = validate(category);
        if (error != null) {
            return error;
        }

        //检查类目名称是否已经存在
        if(category != null){
            List<LitemallCategory> categories =  litemallCategoryService.queryByName(category.getName());

            if(categories.size() > 0){
                return ResponseUtil.fail(111,"商品分类名称已存在");
            }
        }

        litemallCategoryService.add(category);
        return ResponseUtil.ok(category);
    }

    /**
     * 读
     *
     * @param id id
     * @return {@link Object}
     */
    @GetMapping("/read")
    @LogAnno
    @ApiOperation("读取分类详情")
    public Object read(@NotNull @RequestParam(value = "id") Integer id) {
        LitemallCategory category = litemallCategoryService.findById(id);
        return ResponseUtil.ok(category);
    }

    /**
     * 更新
     *
     * @param category 类别
     * @return {@link Object}
     */
    @PostMapping("/update")
    @LogAnno
    @ApiOperation("更新分类")
    public Object update(@RequestBody LitemallCategory category) {
        Object error = validate(category);
        if (error != null) {
            return error;
        }

        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(category.getId());
        categoryService.getSubIds(category.getId(), categoryIds);
        /*if(litemallGoodsService.countByCategoryIds(categoryIds) > 0){
            return ResponseUtil.fail(GOODS_CATEGORY_HAS_GOODS, "该分类下面有商品，不能修改");
        }*/

        if (litemallCategoryService.updateById(category) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    /**
     * 删除
     *
     * @param category 类别
     * @return {@link Object}
     */
    @PostMapping("/delete")
    @LogAnno
    @ApiOperation("删除分类")
    public Object delete(@RequestBody LitemallCategory category) {
        return categoryService.delete(category);
    }

    /**
     * 猫l1
     *
     * @return {@link Object}
     */
    @GetMapping("/l1")
    @LogAnno
    @ApiOperation("获取一级分类（下拉用）")
    public Object catL1() {
        // 所有一级分类目录
        List<LitemallCategory> l1CatList = litemallCategoryService.queryL1();
        List<Map<String, Object>> data = new ArrayList<>(l1CatList.size());
        for (LitemallCategory category : l1CatList) {
            Map<String, Object> d = new HashMap<>(2);
            d.put("value", category.getId());
            d.put("label", category.getName());
            data.add(d);
        }
        return ResponseUtil.okList(data);
    }

    /**
     * 猫l2
     *
     * @return {@link Object}
     */
    @GetMapping("/l2")
    @LogAnno
    @ApiOperation("获取一、二级分类")
    public Object catL2() {
        // 所有一、二级分类目录
        return categoryService.queryL2();
    }

    @GetMapping("/level1")
    @LogAnno
    @ApiOperation("获取所有一级分类")
    public Object getLevel1Categories() {
        List<LitemallCategory> level1 = litemallCategoryService.queryByLevel("L1");
        return ResponseUtil.ok(level1);
    }

    @GetMapping("/level2")
    @LogAnno
    @ApiOperation("根据一级分类ID获取二级分类")
    public Object getLevel2Categories(@RequestParam("pid") Integer pid) {
        List<LitemallCategory> level2 = litemallCategoryService.queryByPid(pid);
        return ResponseUtil.ok(level2);
    }

    @GetMapping("/level3")
    @LogAnno
    @ApiOperation("根据二级分类ID获取三级分类")
    public Object getLevel3Categories(@RequestParam("pid") Integer pid) {
        List<LitemallCategory> level3 = litemallCategoryService.queryByPid(pid);
        return ResponseUtil.ok(level3);
    }
}
